import walletIcon from 'src/assets/wallet.svg';
import activityIcon from 'src/assets/activity.svg';
import cattleIcon from 'src/assets/cattle.svg';
import cmsIcon from 'src/assets/cms.svg';
import mallIcon from 'src/assets/mall.svg';
import messageIcon from 'src/assets/message.svg';
import niujuanIcon from 'src/assets/niujuan.svg';
import factoryIcon from 'src/assets/factory.svg';
import pastureVedioIcon from 'src/assets/pasture-vedio.svg';
import { getAllPeriods, initUser, checkIsPcLogin, getAllNotification } from 'config/api';
import img1Src from 'src/assets/cattle1.jpg';
import img2Src from 'src/assets/cattle2.jpg';
import img3Src from 'src/assets/cattle3.jpg';
import router from 'umi/router';
import { Toast } from 'antd-mobile';
import { mobileShopUrl } from 'config';
export default {
  namespace: 'main',
  state: {
    latestPeriod: {},
    notifications: [],
    loginToken: '',
    carouselData: [
      {
        url: '',
        key: '1',
        imgSrc: img1Src
      },
      {
        url: '',
        key: '2',
        imgSrc: img2Src
      },
      {
        url: '',
        key: '3',
        imgSrc: img3Src
      }
    ],
    imgHeight: 100,
    menuData: [
      {
        name: '预期年分红',
        data: '20%'
      },
      {
        name: '每只/元',
        data: '1000'
      },
      {
        name: '期限',
        data: '12个月'
      }
    ],
    gridData: [
      {
        icon: walletIcon,
        text: '我的钱包',
        url: '/wallet'
      },
      {
        icon: cattleIcon,
        text: '购买牛只',
        url: '/layout/periodList?tabName=main'
      },
      {
        icon: mallIcon,
        text: '生活商城',
        url: mobileShopUrl
        // url: 'http://shop.niushengniu.cn/'
        // url: 'http://nsnshop.huangyanyang.cn/'
      },
     {
        icon: pastureVedioIcon,
        text: '牧场视频',
        url: '/layout/factoryVedio?tabName=main&page=2'
      },
      // {
      //   icon: activityIcon,
      //   text: '活动专区',
      //   url: '/layout/activity?tabName=main'
      // },
      {
        icon: niujuanIcon,
        text: '我的牛圈',
        url: '/layout/myLarn?tabName=main'
      },
      {
        icon: cmsIcon,
        text: '平台资讯',
        url: '/layout/cms?tabName=main&page=0'
      },
      // {
      //   icon: factoryIcon,
      //   text: '工厂视频',
      //   url: '/layout/factoryVedio?tabName=main&page=1'
      // },
      // {
      //   icon: pastureVedioIcon,
      //   text: '牧场视频',
      //   url: '/layout/factoryVedio?tabName=main&page=2'
      // },
      // {
      //   icon: messageIcon,
      //   text: '我的消息',
      //   url: '/layout/record?tabName=muniuren&title=我的消息'
      // }
    ],
    footerIconUrl: require('src/assets/cattle.svg'),
    footerActivityText: '牛牛换新装，买牛送福利'
  },
  reducers: {
    changeImgHeight(state, imgHeight) {
      return { ...state, imgHeight };
    },
    saveLatestPeriod(state, { latestPeriod, menuData }) {
      return { ...state, latestPeriod, menuData };
    },
    save(state, { payload }) {
      return { ...state, ...payload };
    }
  },
  effects: {
    *queryLatestPeriod(action, { call, put }) {
      let periods = (yield call(getAllPeriods)).data.list;
      let latestPeriod = periods[0];
      let menuData = [
        {
          name: '预期年分红',
          data: `${latestPeriod.return_rate}%`
        },
        {
          name: '每只/元',
          data: latestPeriod.price
        },
        {
          name: '期限',
          data: `${latestPeriod.term}个月`
        }
      ];
      yield put({
        type: 'saveLatestPeriod',
        latestPeriod,
        menuData
      });
    },
    *goToMobileShopWithToken({ host, hash, query }, { select, call }) {
      console.log('gogoggoo');
      let loginToken = yield select(state => state.main.loginToken);
      if (loginToken) {
        location.href = `${host}${query}loginToken=${loginToken}${hash}`;
      } else {
        Toast.info('请先登录');
      }
    },
    *EInitUser({ code }, { call, put }) {
      let { isLogin, token } = yield call(checkIsPcLogin);

      // alert(isLogin)
      if (isLogin) {
        yield put({
          type: 'save',
          payload: { loginToken: token }
        });
        return;
      }
      let state = 'weixin';
      let nativeWeixinLogin = () => {
        plus.oauth.getServices(
          function(services) {
            console.log('​services', services);
            let auths = services;
            auths[0].authorize(
              function(e) {
                // alert('授权成功：' + JSON.stringify(e));
                initUser(e.code, e.state).then(res => {
                  // alert('​res' + JSON.stringify(res));
                  if (res.code === -1) {
                    Toast.info(res.msg);
                    router.push('/login');
                  } else {
                    Toast.info(res.msg);
                  }
                });
              },
              function(e) {
                // alert('授权失败：' + JSON.stringify(e));
                Toast.info('您取消了登录，必须使用微信登录才能投资牛只');
                nativeWeixinLogin();
              },
              { scope: 'snsapi_userinfo', state: 'mobile', appid: 'wxaf33a644198eb3fa' }
            );
            // authLogin(auths[0]);
          },
          function(e) {
            console.log('获取分享服务列表失败：' + e.message + ' - ' + e.code);
          }
        );
      };
      if (navigator.userAgent.indexOf('Html5Plus') > -1) {
        // alert('11111');
        // if(window.plus){
        //   nativeWeixinLogin()
        // }else{
        //   document.addEventListener(
        //     'plusready',
        //     function() {
        //       // 扩展API加载完毕，现在可以正常调用扩展API
        //       // alert('开始登录')
        //       nativeWeixinLogin()
        //     },
        //     false
        //   );
        // }
        router.push('/login');
      } else {
        let response = yield call(initUser, code, state);
        console.log('​*EInitUser -> response', response);
        if (response.code === -1) {
          Toast.info(response.msg);
          router.push('/login');
        }
        if (response.errcode) {
          Toast.info('请用手机号登录');
          router.push('/login');
        }
        if (response.token) {
          yield put({
            type: 'save',
            payload: { loginToken: response.token }
          });
        }
      }
    },
    *getAllNotificationEff(action, { call, put }) {
      let { list } = yield call(getAllNotification);
      let notifications = list.map(i => i.content);
      yield put({
        type: 'save',
        payload: { notifications }
      });
    }
  }
};
